package com.hnjk.cbts;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class ConfigProperties {

    private static final String propertyFilePath = "config/config.txt".replace('/', File.separatorChar);

    private static Properties p = new Properties();

    //获取配置属性
    public static String getConfig(String key){
        try{
            p.load(new FileInputStream(propertyFilePath));
            return p.getProperty(key);
        }catch(Exception e){
            e.printStackTrace();
        }
        return "";
    }

    public static void saveConfig(String key ,String value){
        try{
            p.setProperty(key, value);
            p.store(new FileOutputStream(propertyFilePath), "config.txt");
        }catch(Exception e){
            e.printStackTrace();
        }

    }

    // 获取一组配置属性
    public static Map<String, String> getConfigGroup(String grpKey) {
        Map<String, String> group = new HashMap<>();
        Set<Object> keys = p.keySet();
        for(Object key : keys) {
            String keyStr = key.toString();
            String[] tmp = keyStr.split("\\.");
            if(tmp.length > 0 && grpKey.equals(tmp[0])) {
                group.put(tmp[1], getConfig(keyStr));
            }
        }
        return group;
    }

    // 获取一组配置属性,返回数组,暂时不实现。
    /*
    public static String[] getConfigGroupArray(String grpKey) {
        String[] grpArray = null;

        return grpArray;
    }*/

    public static void main(String[] args) throws Exception{
        System.out.println(getConfig("proxy"));
        String test = getConfig("host.wl");
        System.out.println(test);
        saveConfig("version","1.0");
        System.out.println(getConfig("version"));

        System.out.println(getConfigGroup("host").toString());
        System.out.println(getConfigGroup("test").toString());

    }
}